package org.jcms.service.impl;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jcms.model.Book;
import org.jcms.model.Customer;
import org.jcms.model.Order;
import org.jcms.model.OrderBook;
import org.jcms.model.OrderBookId;
import org.jcms.service.CustomerServiceI;
import org.jcms.service.StateServiceI;
import org.jcms.service.base.GenericDaoImpl;
import org.jcms.uitils.DateUtil;
import org.jcms.uitils.RandomUUID;
import org.json.JSONArray;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Transactional
@Service
public class CustomerServiceImpl extends GenericDaoImpl<Customer> implements
		CustomerServiceI {
@Resource
private StateServiceI stateServiceI;
	@Override
	public void buildOrder(Customer customer, JSONArray jsonArray,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		org.hibernate.classic.Session session = sessionFactory
				.getCurrentSession();

		Double orderSum = 0.0;

		Order order = new Order();
		order.setOrderId(RandomUUID.getRandomUUID());
		order.setCustomer(customer);
		order.setState(stateServiceI.findById(0));
		order.setOrderTime(DateUtil.nowTime());
		order.setOrderSum(orderSum);
		session.save(order);
		for (int i = 0; i < jsonArray.length(); i++) {
			Book book = (Book) session.get(Book.class,
					jsonArray.getJSONObject(i).getString("bookIsbn"));
			if (book == null) {
				throw new RuntimeException();
			} else {
				orderSum += (book.getBookPrice() * Integer.parseInt(jsonArray
						.getJSONObject(i).getString("orderBookNumber")));
				OrderBook orderBook = new OrderBook();
				orderBook.setId(new OrderBookId(order, book));
				orderBook.setOrderBookNumber(Integer.parseInt(jsonArray
						.getJSONObject(i).getString("orderBookNumber")));
				orderBook.setOrderBookPrice(book.getBookPrice());
				session.save(orderBook);
			}
		}
		
		order.setOrderSum(orderSum);
	}

}
